package com.example.demo.service.impl;

import com.example.demo.service.IFirstDemoService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class FirstDemoService implements IFirstDemoService {

    //加入公司操作，可从DelegateExecution获取流程中的变量
    @Override
    public void joinGroup(DelegateExecution execution) {
        Boolean bool = (Boolean) execution.getVariable("joinApproved");
        if (bool) {
            Long personId = (Long) execution.getVariable("personId");
            Long compId = (Long) execution.getVariable("compId");
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>  将员工加入集体");
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>  加入组织成功");
        } else {
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>  加入组织失败");
        }
    }

    //获取符合条件的审批人，演示这里写死，使用应用使用实际代码
    @Override
    public List<String> findUsers(DelegateExecution execution) {
        return Arrays.asList("admin", "wtr");
    }


    //注入为我们自动配置好的服务
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    //开始流程，传入申请者的id以及公司的id
    @Override
    @Transactional
    public void startProcess(Long personId, Long compId) {
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("personId", personId);
        variables.put("compId", compId);
        runtimeService.startProcessInstanceByKey("joinProcess", variables);
    }

    //获得某个人的任务别表
    @Override
    @Transactional
    public List<Task> getTasks(String assignee) {
        return taskService.createTaskQuery().taskCandidateUser(assignee).list();
    }

    //完成任务
    @Override
    @Transactional
    public void completeTasks(Boolean joinApproved, String taskId) {
        Map<String, Object> taskVariables = new HashMap<String, Object>();
        taskVariables.put("joinApproved", joinApproved);
        taskService.complete(taskId, taskVariables);
    }
}
